package com.ly.blog2Admin.handler;


import com.ly.blog2Common.utils.IPUtils;
import com.ly.blog2Common.utils.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 过滤器
 * create by lyMaster on 2019/10/10 - 12:38
 **/
@Component
@WebFilter(urlPatterns = "/*", filterName = "myFilter" )
@Log4j2
public class MyFilter implements Filter {



    @Override
    public void init(FilterConfig arg0){
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        //非期望URL不做日志输出，减少日志代码量
        if(!StringUtils.isUrlFilter(((HttpServletRequest) servletRequest).getRequestURI())){
            String ip = IPUtils.getIpAddr((HttpServletRequest) servletRequest);
            log.info("URL（资源路径）:{};   PARAM（参数信息）:{};   CLIENT_IP（客户端IP）:{};   CLIENT_NAME（客户端名称）:{}"
                    ,((HttpServletRequest) servletRequest).getRequestURI()
//                    ,getRequestPayload((HttpServletRequest) servletRequest)
                    ,(servletRequest).getParameterMap()
                    ,ip
                    ,servletRequest.getRemoteHost());
        }

        //记录访问请求
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        log.info("过滤器销毁");
    }


    private String getRequestPayload(HttpServletRequest req) {
        ServletInputStream is = null;
        try {
            is = req.getInputStream();
            int nRead = 1;
            int nTotalRead = 0;
            byte[] bytes = new byte[10240];
            while (nRead > 0) {
                nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
                if (nRead > 0)
                    nTotalRead = nTotalRead + nRead;
            }
            String str = new String(bytes, 0, nTotalRead, "utf-8");
            return str;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
//            if(is != null){
//                try {
//                    is.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
        }
    }
}
